package czk.concrent.threadpool.threadfactory;

import java.util.Arrays;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程池工厂
 *
 * @Author:ChenZhangKun
 * @Date: 2023/4/8 14:59
 */
public class OwnThreadFactory implements ThreadFactory {
    // 第几个线程池，方便区分，静态，所有线程工厂一起计数
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup threadGroup;
    // 第几个线程数,非静态，每个对象独享
    private  final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;
    private final String threadFactoryName;

    public OwnThreadFactory(String threadStartName) {
        SecurityManager s = System.getSecurityManager();
        // 哪个线程组
        threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = threadStartName + "-pool-" + poolNumber.getAndIncrement() + "-thread-";
        threadFactoryName = threadStartName;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(threadGroup, r, namePrefix + threadNumber.getAndIncrement(),0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        t.setUncaughtExceptionHandler((t1,e)->{
            String name = t1.getName();
            System.out.println(name+"线程发生异常了==="+ Arrays.toString(e.getStackTrace()));
        });
        return t;
    }
}
